package cuiying.rbac.service.array;

import cuiying.rbac.domain.dto.BaseDto;
import cuiying.rbac.domain.dto.DeptDto;
import cuiying.rbac.domain.entity.BaseEntity;
import cuiying.rbac.domain.entity.Dept;
import cuiying.rbac.domain.vo.BaseVo;
import cuiying.rbac.domain.vo.DeptVo;
import cuiying.rbac.domain.vo.Result;
import cuiying.rbac.service.IBaseService;

import java.util.Arrays;

/**
 * 业务层-基类
 *
 * @author 崔颖
 * @since 2025/6/1 21:55
 */
abstract class BaseService<Entity extends BaseEntity,Dto extends BaseDto,
        Vo extends BaseVo>
        implements IBaseService<Entity,Dto> {

    static final int DATA_SIZE = 100;
    Entity[] data;
    Vo[] temp;

    private int idCounter = 1;

    @Override
    public boolean existsById(int id) {
        return id >=1 &&id<idCounter && data[id] !=null;
    }
    @Override
    public Entity findById(int id) {
        if(!existsById(id)){
            return data[id];
        }
        return null;
    }

    abstract Vo converToVo(Entity entity);

    @Override
    public Result list() {
        int length = 0;
        for(int i = 1;i < idCounter;i++){
            if(data[i]!=null){
                temp[length++] = converToVo(data[i]);
            }
        }
        return Result.success("查询成功", Arrays.copyOf(temp,length));
    }
    abstract Entity createEntity(Dto dto,int id);

    @Override
    public Result create(Dto dto) {
        if(idCounter>DATA_SIZE){
            return Result.failure("创建失效，超出了存储容量");
        }
        //Dept dept = new Dept(dto.name, dto.phone);
        //dept.id = idCounter++;
        Entity entity = createEntity(dto,idCounter++);
        data[entity.getId()] = entity;
        return Result.success("创建成功", null);
    }
    abstract void updataEntity(Dto dto, Entity entity);


    @Override
    public Result updata(Dto dto, int id) {
        if(!existsById(id)){
            return Result.failure("更新失败，不存在该数据");
        }
        Entity entity = data[id];
        updataEntity(dto,entity);
        return Result.success("更新成功",null);
    }

}